package com.doge.calcalbum.business.entry

import com.doge.calcalbum.db.model.AlbumCover
import com.doge.calcalbum.db.model.Entry
import com.doge.calcalbum.utils.db
import com.doge.calcalbum.utils.runInTransaction

class EntryRepository(val albumId: Int) {
    val entryList = db.entryDao().queryLiveData(albumId)
    val album = db.albumDao().queryByIdLiveData(albumId)
    fun insert(entry: Entry) = runInTransaction {
        db.entryDao().insert(entry)
        db.albumDao().updateCount(albumId)
    }

    fun markDeleted(entries: List<Entry>) = runInTransaction {
        entries.forEach { db.entryDao().markDeleted(it.id) }
        db.albumDao().updateCount(albumId)

        val album = db.albumDao().queryById(albumId)
        if (entries.any { it.id == album?.coverEntryId }) {
            db.entryDao().queryOne(albumId).let {
                db.albumDao().updateCover(AlbumCover(albumId, it?.id))
            }
        }
    }

    fun moveToAlbum(entries: List<Entry>, targetId: Int) = runInTransaction {
        val album = db.albumDao().queryById(albumId)

        entries.map { it.copy(albumId = targetId) }.forEach(db.entryDao()::update)

        if (entries.any { it.id == album?.coverEntryId }) {
            db.entryDao().queryOne(albumId).let {
                db.albumDao().updateCover(AlbumCover(albumId, it?.id))
            }
        }

        if (db.albumDao().queryById(targetId)?.coverEntryId == null) {
            db.entryDao().queryOne(targetId).let {
                db.albumDao().updateCover(AlbumCover(targetId, it?.id))
            }
        }

        db.albumDao().updateCount(albumId)
        db.albumDao().updateCount(targetId)
    }

}